package com.tom.architect02.zframework.wms.skin.higher_lib;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.view.LayoutInflater;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.tom.architect02.zframework.wms.skin.higher_lib.utils.SkinFactory;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

// 监听app的 activity。
public class MyApplicationLifecycle implements Application.ActivityLifecycleCallbacks {
    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        setFactory(activity);
//        Log.e("Maniu", activity.getClass().getName());
    }

    public static Map<Activity, SkinFactory> activitySkinFactoryMap = new HashMap<>();

    @SuppressLint("SoonBlockedPrivateApi")
    private void setFactory(Activity activity) {
        SkinFactory skinLayoutInflaterFactory = new SkinFactory();
        try {
            Field mFactorySet = LayoutInflater.class.getDeclaredField("mFactorySet");
            mFactorySet.setAccessible(true);
            mFactorySet.setBoolean(activity.getLayoutInflater(), false);
            activity.getLayoutInflater().setFactory2(skinLayoutInflaterFactory);
            activitySkinFactoryMap.put(activity, skinLayoutInflaterFactory); // 缓存起来
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {
        apply(); // 刷新UI。
    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    public void apply() {
        for (Map.Entry<Activity, SkinFactory> entry : activitySkinFactoryMap.entrySet()) {
            entry.getValue().apply();
        }
    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        activitySkinFactoryMap.remove(activity);
    }
}
